package com.lq.ecoldchain.internet

import com.alibaba.android.arouter.launcher.ARouter
import com.lq.ecoldchain.base.BaseNavigator
import com.lq.ecoldchain.base.view.App
import com.lq.ecoldchain.callback.LifeCallBack
import com.lq.ecoldchain.ui.login.LoginActivity
import com.lq.ecoldchain.util.log
import okhttp3.*
import java.nio.charset.Charset
import org.json.JSONObject


/*
*2018/12/14 0014  15:58
*重新获取token  by lq
*/
class TokenInterceptor : Interceptor {
    private val UTF8 = Charset.forName("UTF-8")

    override fun intercept(chain: Interceptor.Chain): Response {
        val request = chain.request()
        log { "${request.url()}" }
        val originalResponse = chain.proceed(request)
        val responseBody = originalResponse.body()
        val source = responseBody!!.source()
        source.request(Long.MAX_VALUE) // Buffer the entire body.
        val buffer = source.buffer()
        var charset = UTF8
        val contentType = responseBody.contentType()
        if (contentType != null) {
            charset = contentType.charset(UTF8)
        }
        val bodyString = buffer.clone().readString(charset)
       log { bodyString }
        if (!bodyString.isEmpty()) {
            val json = JSONObject(bodyString)
            val code = json.getString("code")
            if (code == "401") {
                //重新请求
                LifeCallBack.finishAll()
                ARouter.getInstance().build(BaseNavigator.login).navigation()
            }
        }
        return originalResponse
    }
}